# We define the test module.  The test module depends on a number of Javascript
# files, which must all be downloaded before the module can execute.
define [
	'jquery'
	'helper'
	'processing'
	'jqcouch'
], ($, H) ->

	$.fn.pl_test = (S) ->

		unless @pl_plugin()
			@pl_plugin 'test'
			return @

		# Run the test sequence each time this plugin is applied.
		$results = $('#results', @)
		$.subscribe 'pl.test', (e, x) => $results.append $('<li>').text x

		# Test that jquery.couch is available by having it connect to the
		# project database and showing its name.
		db = $.couch.db 'bc_public_libraries'
		$.publish 'pl.test', "connected to database #{db.name}"

		$.get('http://localhost:5984/bc_public_libraries/_design/patrons_percap/_view/Patrons%20per%20capita', (data) ->

			$.publish 'pl.test', "Patrons per Capita"

			# Sort data set by population size, descending
			data.rows.sort (a, b) -> b.value.pop - a.value.pop
			xMax = data.total_rows
			yMax = 200

			canvasElem = ($canvas = $('<canvas>')).get(0)
			new Processing canvasElem, (P) ->
				P.setup = ->

					# Set up colour settings
					colourDark = P.color 128
					colourLight = P.color 255
					P.fill colourLight
					P.background colourDark
					P.noStroke()

					barWidth = 5
					P.size xMax * barWidth, yMax
					bar_xy = (x, y) -> P.rect x * barWidth, 0, barWidth, y
					bar_xy(n, o.value.percap) for o, n in data.rows
					$results.append $canvas
					return
		, 'json')

		$.get('http://localhost:5984/bc_public_libraries/_design/patrons_percap/_view/Circulations%20per%20capita', (data) ->

			$.publish 'pl.test', "Circulations per Capita"

			# Sort data set by population size, descending
			data.rows.sort (a, b) -> b.value.pop - a.value.pop
			xMax = data.total_rows
			yMax = 200

			ymax = (_.max data.rows, (y) -> y.value.percap).value.percap
			yFactor = yMax / ymax

			canvasElem = ($canvas = $('<canvas>')).get(0)
			new Processing canvasElem, (P) ->
				P.setup = ->

					# Set up colour settings
					colourDark = P.color 128
					colourLight = P.color 255
					P.fill colourLight
					P.background colourDark
					P.noStroke()

					barWidth = 5
					P.size xMax * barWidth, yMax
					bar_xy = (x, y) -> P.rect x * barWidth, 0, barWidth, y
					bar_xy(n, o.value.percap * yFactor) for o, n in data.rows
					$results.append $canvas
					return
		, 'json')

		return @
	return
